package com.gitee.free.coding.core.utils;

import com.gitee.free.coding.core.exceptions.FreeRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

@Slf4j
public class Encipher {

    /**
     * 密钥
     */
    public static final String secretKey = "free-coding-secret-key";

    static {
        // BouncyCastleProvider 实例化时，name 默认赋值 BC
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * HmacSHA256 加密
     *
     * @param plainText 明文
     * @return 密文
     */
    public static String encryptWithHmacSHA256(String plainText) {
        log.info("明文：{}", plainText);
        if (StringUtils.isBlank(plainText)) {
            throw new FreeRuntimeException(-1, "需要加密的明文内容不能为空");
        }
        try {
            // 密钥【应该是安全的随机字节】
            byte[] key = secretKey.getBytes(StandardCharsets.UTF_8);
            // 初始化 HMAC-SHA256 Mac 实例
            Mac hmacSha256 = Mac.getInstance("HmacSHA256", "BC");
            hmacSha256.init(new SecretKeySpec(key, "HmacSHA256"));
            // 更新要签名的消息
            hmacSha256.update(plainText.getBytes(StandardCharsets.UTF_8));
            // 完成签名计算
            byte[] hmac = hmacSha256.doFinal();
            // 将签名转换为十六进制字符串，方便查看
            StringBuilder sb = new StringBuilder();
            for (byte b : hmac) {
                sb.append(String.format("%02x", b & 0xff));
            }
            String hexHmac = sb.toString();
            log.info("HMAC-SHA256: {}", hexHmac);
            return hexHmac;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new FreeRuntimeException(-1, "加密失败");
        }
    }
}
